package org.learn.supports.spring.autoproxy;

import org.springframework.aop.TargetSource;
import org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;



public abstract class BeanAwareLifeCycleHook extends AbstractAutoProxyCreator implements InitializingBean,ApplicationContextAware,DisposableBean {

    private BeanAwareHookContext beanAwareHookContext = new BeanAwareHookContext();


    @Override
    protected Object wrapIfNecessary(Object bean, String beanName, Object cacheKey){
        if(this.wrapIfNecessary(bean,beanName,cacheKey,beanAwareHookContext))
            return super.wrapIfNecessary(bean,beanName,cacheKey);
        return bean;
    }



    abstract protected boolean wrapIfNecessary(Object bean, String beanName, Object cacheKey,BeanAwareHookContext beanAwareHookContext);



    protected Object[] getAdvicesAndAdvisorsForBean(Class<?> beanClass, String beanName, TargetSource customTargetSource) throws BeansException {
        return new Object[] {beanAwareHookContext.getInterceptor()};
    }



    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        beanAwareHookContext.setApplicationContext(applicationContext);
        this.setBeanFactory(applicationContext);
    }



    public BeanAwareHookContext getBeanAwareHookContext() {
        return beanAwareHookContext;
    }

    public void setBeanAwareHookContext(BeanAwareHookContext beanAwareHookContext) {
        this.beanAwareHookContext = beanAwareHookContext;
    }
}
